import {
  getMessageList,
  getNotReadCount,
  postUpdateReadStatus,
  postUpdateAllReadStatus,
  postDeleteMessage,
 } from './services';

 const formatJson = (data) =>{
   return {
     ...data,
    list : data.list,
    pagination :{
      ...data.pagination,
      showSizeChanger: true,
      showQuickJumper: true,
      current: data.pageNum,
      // sorter: {
      //   order: asc ? `${asc}end` : ``,
      //   field: order
      // },
      total: data.total,
      pageSize: data.pageSize,
      showTotal: counts => `总共 ${counts} 条`,
      pageSizeOptions: [
        "5",
        "10",
        "20",
        "30",
        "40",
        "50",
        "60",
        "70",
        "80",
        "90",
        "100"
      ]
    }
  }
 }

export default {
  namespace: 'messages',
  state: {
      selectedRowKeys: [],
      count:0,
      data: {
        list: [],
        pagination: {
          showSizeChanger: true,
          showQuickJumper: true,
          pageSize: 10,
          showTotal: total => `总共 ${total} 条`,
          pageSizeOptions: [
            "5",
            "10",
            "20",
            "30",
            "40",
            "50",
            "60",
            "70",
            "80",
            "90",
            "100"
          ]
        }
      },
  },
  effects: {
    *fetchMessageList({ payload }, { call, put }) {
      const response = yield call(getMessageList, payload);
      //console.log(response)
      const { code, data } = response
      if(code === 1){
        yield put({
          type: 'save',
          payload: data,
        });
      }
    },
    *fetchNotReadCount({ payload }, { call, put }) {
      const response = yield call(getNotReadCount);
      //console.log(response)
      const { code, data } = response
      if (code === 1) {
        yield put({
          type: 'saveCount',
          payload: data,
        });
      }
    },
    *getUpdateReadStatus({ payload }, { call, put }) {
      const response = yield call(postUpdateReadStatus, payload);
      const { code, msg } = response
      if (code === 1) {
        return Promise.resolve(msg)
      }
      return Promise.reject(msg)
    },
    *getUpdateAllReadStatus({ payload }, { call, put }) {
      const response = yield call(postUpdateAllReadStatus);
      const { code, msg } = response
      if (code === 1) {
        return Promise.resolve(msg)
      }
      return Promise.reject(msg)
    },
    *getDeleteMessage({ payload }, { call, put }) {
      const response = yield call(postDeleteMessage, payload)
      const { code, msg } = response
      if (code === 1) {
        return Promise.resolve(msg)
      }
      return Promise.reject(msg)
    }
  },
  reducers: {
    save(state, { payload }) {
      state.data = formatJson(payload)
      return state
    },
    saveCount(state, { payload }) {
      state.count = payload
      return state
    }
  },
};
